package com.lw.leetcode.arr.b;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 1992. 找到所有的农场组
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/5 14:36
 */
public class FindFarmland {

    private int m;
    private int n;
    private int[][] land;
    private List<Long> list = new ArrayList<>();

    public int[][] findFarmland(int[][] land) {
        this.land = land;
        this.m = land.length;
        this.n = land[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (land[i][j] == 1) {
                    list.add(((long) i << 36) + ((long) j << 24) + find(i, j));

                }
            }
        }
        int size = list.size();
        int[][] arr = new int[size][4];
        for (int i = 0; i < size; i++) {
            long value = list.get(i);
            arr[i][0] = (int) (value >> 36);
            arr[i][1] = (int) ((value & 0XFFFFFFFFFL) >> 24);
            arr[i][2] = (int) ((value & 0XFFFFFFL) >> 12);
            arr[i][3] = (int) (value & 0XFFFL);
        }
        return arr;
    }

    private int find(int x, int y) {
        int i = x;
        for (; i < m; i++) {
            if (land[i][y] == 0) {
                break;
            }
        }
        int j = y;
        for (; j < n; j++) {
            if (land[x][j] == 0) {
                break;
            }
        }
        for (int k1 = x; k1 < i; k1++) {
            for (int k2 = y; k2 < j; k2++) {
                land[k1][k2] = 0;
            }
        }
        return ((i - 1) << 12) + j - 1;
    }

}
